import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from './trpc/router';
import { createTRPCContext } from './trpc/context';
import { ImportService } from './services/importService';
import { TimerService } from './services/timerService';

const app = new Hono();

// 中间件
app.use('*', logger());
app.use('*', cors({
  origin: ['*'], // 允许前端访问
  allowHeaders: ['Content-Type', 'Authorization', 'x-trpc-source'],
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  credentials: true,
}));

// 健康检查端点
app.get('/health', (c) => {
  return c.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    service: 'vue-turbo-stack-api'
  });
});

// 文件上传解析端点
app.post('/api/upload/parse-file', async (c) => {
  try {
    const formData = await c.req.formData();
    const file = formData.get('file') as File;

    if (!file) {
      return c.json({
        success: false,
        message: '没有找到上传的文件',
        code: 'NO_FILE_UPLOADED'
      }, 400);
    }

    // 检查文件类型
    const allowedTypes = ['text/csv', 'text/plain', 'application/csv'];
    const allowedExtensions = ['.csv', '.txt'];
    const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));

    if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension)) {
      return c.json({
        success: false,
        message: '不支持的文件类型，请上传 CSV 或 TXT 文件',
        code: 'INVALID_FILE_TYPE'
      }, 400);
    }

    // 检查文件大小（限制为 10MB）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      return c.json({
        success: false,
        message: '文件大小超过限制（最大 10MB）',
        code: 'FILE_TOO_LARGE'
      }, 400);
    }

    // 将文件转换为 Buffer
    const arrayBuffer = await file.arrayBuffer();
    const fileBuffer = Buffer.from(arrayBuffer);

    // 调用 ImportService 解析文件
    const result = await ImportService.parseFile({
      fileBuffer,
      fileName: file.name,
    });

    return c.json(result);
  } catch (error) {
    console.error('文件上传解析失败:', error);
    return c.json({
      success: false,
      message: '文件上传解析失败',
      code: 'UPLOAD_PARSE_ERROR',
      error: error instanceof Error ? error.message : String(error)
    }, 500);
  }
});

// tRPC 路由
app.use('/trpc/*', async (c) => {
  return fetchRequestHandler({
    endpoint: '/trpc',
    req: c.req.raw,
    router: appRouter,
    createContext: () => createTRPCContext(c),
  });
});

// 404 处理
app.notFound((c) => {
  return c.json({ error: 'Not Found' }, 404);
});

// 错误处理
app.onError((err, c) => {
  console.error('Server error:', err);
  return c.json({ 
    error: 'Internal Server Error',
    message: err.message 
  }, 500);
});

const port = process.env.PORT || 3017;

// 启动所有定时器
TimerService.startAllTimers();

// 优雅关闭处理
process.on('SIGINT', () => {
  console.log('\n收到 SIGINT 信号，开始优雅关闭...');
  TimerService.stopAllTimers();
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n收到 SIGTERM 信号，开始优雅关闭...');
  TimerService.stopAllTimers();
  process.exit(0);
});

console.log(`🚀 Server running on http://localhost:${port}`);
console.log(`📡 tRPC endpoint: http://localhost:${port}/trpc`);
console.log(`🏥 Health check: http://localhost:${port}/health`);
console.log(`⏰ All timers started (including auto cleanup every 5 minutes)`);

export default {
  port,
  fetch: app.fetch,
};
